package user

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/utils"
)

func Ywdkefu(c *gin.Context) {
	url := "http://zdb.suishilian.com/upload/yewudaoerweima.png"
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    url,
		"msg":     "ok",
	})
	return
}
func Buypackages(c *gin.Context) {
	var pkg []models.Buypackage
	data_source.Db.Find(&pkg)
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    pkg,
		"msg":     "ok",
	})
	return
}

func Wxtoken(c *gin.Context) {
	token := "zhangdan_wechat_token" // 替换成你自己的token

	signature := c.Query("signature")
	timestamp := c.Query("timestamp")
	nonce := c.Query("nonce")
	echostr := c.Query("echostr")

	if checkSignature(token, signature, timestamp, nonce) {
		c.String(http.StatusOK, echostr)
	} else {
		c.String(http.StatusBadRequest, "Invalid request")
	}
}

func checkSignature(token, signature, timestamp, nonce string) bool {
	// 根据微信公众号开发文档提供的规则进行签名校验
	// 返回 true 或 false

	return true // 在这里替换成你的签名校验逻辑
}

func Provinces(ctx *gin.Context) {

	var citys []models.Citynew
	data_source.Db.Find(&citys)
	result := getListGoods(citys, 0, 1)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    result,
		"msg":     "ok",
	})
	return
}
func getListGoods(stuAll []models.Citynew, pid int64, lev int64) []models.Citynew {
	var goodArr []models.Citynew

	for _, v := range stuAll {
		if v.Pid == pid {
			// 这里可以理解为每次都从最原始的数据里面找出相对就的ID进行匹配，直到找不到就返回
			child := getListGoods(stuAll, v.ID, lev+1)
			node := models.Citynew{
				ID:    utils.StrToInt64(v.Code),
				Name:  v.Name,
				Level: lev,
				Pid:   v.Pid,
				List:  child,
			}
			goodArr = append(goodArr, node)
		}
	}
	return goodArr
}

func Classifydr(ctx *gin.Context) {
	data := classifyfl()
	fmt.Println(data.Data.List)
	//return
	for _, v := range data.Data.List {
		cla := models.Classify{
			Title: v.Title,
			Desc:  v.Desc,
			Value: v.Value,
		}
		data_source.Db.Create(&cla)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

type Responsedata struct {
	Status int64        `json:"status"`
	Data   Responselist `json:"data"`
}
type Responselist struct {
	List []Responseclassify `json:"list"`
}
type Responseclassify struct {
	Title string `json:"title"`
	Desc  string `json:"desc"`
	Value string `json:"value"`
}

func classifyfl() (data Responsedata) {
	resp, err := http.Get("https://data.yewudaotech.com/interface.php?token=yanwei123&action=app_info_type")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsedata{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}
